<?php

namespace common\service;

use common\exception\LogicException;
use common\model\RoleModel;
use common\model\SupplierModel;
use common\model\TenantGroupMemberModel;
use common\model\TenantModel;
use common\model\TenantUserModel;
use common\model\TenantAuthenticationModel;
use common\model\TenantStepCategoryLevelModel;
use common\model\UserModel;
use support\SingletonTrait;
use think\Exception;
use support\ErrorCode;

class SupplierService
{
    use SingletonTrait;

    /**
     * @var TenantAuthenticationModel
     */
    private $tenantAuthenticationModel;
    /**
     * @var SupplierModel
     */
    private $supplierModel;

    /**
     * @var OptionsService
     */
    private $optionService;

    public function __construct()
    {
        $this->tenantAuthenticationModel = model(TenantAuthenticationModel::class);
        $this->supplierModel = model(SupplierModel::class);
        $this->optionService = new OptionsService();
    }

    /**
     * @param $param
     * @param $filter
     * @return array
     */
    public function select($param, $filter)
    {

        if (array_key_exists('page', $param)) {
            $page = join(',', $param['page']);
        } else {
            $maxPageSize = C("database.database_max_select_rows");
            $page = "1, {$maxPageSize}";
        }


        $supplierModel = model(SupplierModel::class);

        // 获取总行数
        $total = $supplierModel
            ->join("user ON user.id=supplier.user_id", 'LEFT')
            ->join("tenant ON tenant.id=supplier.from_tenant_id", 'LEFT')
            ->join("LEFT JOIN tenant_authentication ON tenant_authentication.tenant_id = supplier.from_tenant_id")
            ->join("LEFT JOIN tenant_user ON supplier.user_id = tenant_user.user_id AND supplier.from_tenant_id = tenant_user.tenant_id")
            ->join('tenant_user_department on tenant_user_department.tenant_user_id = tenant_user.id', 'LEFT')
            ->join('tenant_user_role on tenant_user_role.tenant_user_id = tenant_user.id', 'LEFT')
            ->join("role ON role.id = tenant_user_role.role_id", 'LEFT')
            ->join("department ON department.id = tenant_user_department.department_id", 'LEFT')
            ->where($filter)
            ->field('count(distinct supplier.id ) as total')
            ->find();
        $total = $total['total'] ?? 0;
        // 查询数据
        $data = [];
        if ($total > 0) {
            $queryFields = [
                'supplier.id',
                'supplier.user_id',
                'supplier.type',
                'supplier.tenant_id',
                'supplier.from_tenant_id',
                'supplier.step_category_ids',
                'supplier.created',
                'supplier.updated',
                'supplier.created_by',
                'supplier.framework_agreement_contract_id',
                'supplier.framework_agreement_status',
                'supplier.confirm_status',
                'supplier.create_tenant_id',
                'user.name as user_name',
                'user.phone',
                'tenant.name as from_tenant_name',
                'tenant.nature as from_tenant_nature',
                'tenant_user.id as tenant_user_id',
                'department.name as department_name',
                'role.name as role_name',
            ];
            $data = $supplierModel
                ->join("LEFT JOIN user ON user.id=supplier.user_id")
                ->join("LEFT JOIN tenant ON tenant.id=supplier.from_tenant_id")
                ->join("LEFT JOIN tenant_authentication ON tenant_authentication.tenant_id = supplier.from_tenant_id")
                ->join("LEFT JOIN tenant_user ON supplier.user_id = tenant_user.user_id AND supplier.from_tenant_id = tenant_user.tenant_id")
                ->join('tenant_user_department on tenant_user_department.tenant_user_id = tenant_user.id', 'LEFT')
                ->join('tenant_user_role on tenant_user_role.tenant_user_id = tenant_user.id', 'LEFT')
                ->join("role ON role.id = tenant_user_role.role_id", 'LEFT')
                ->join("department ON department.id = tenant_user_department.department_id", 'LEFT')
                ->field('supplier.id')
                ->where($filter)
                ->group('supplier.id')
                ->page($page)
                ->order('supplier.created desc')
                ->select();
            $supplierIdList = array_column($data, 'id', 'id');
            $data = [];
            if (count($supplierIdList) > 0) {
                $data = $supplierModel
                    ->join("LEFT JOIN user ON user.id=supplier.user_id")
                    ->join("LEFT JOIN tenant ON tenant.id=supplier.from_tenant_id")
                    ->join("LEFT JOIN tenant_authentication ON tenant_authentication.tenant_id = supplier.from_tenant_id")
                    ->join("LEFT JOIN tenant_user ON supplier.user_id = tenant_user.user_id AND supplier.from_tenant_id = tenant_user.tenant_id")
                    ->join('tenant_user_department on tenant_user_department.tenant_user_id = tenant_user.id', 'LEFT')
                    ->join('tenant_user_role on tenant_user_role.tenant_user_id = tenant_user.id', 'LEFT')
                    ->join("role ON role.id = tenant_user_role.role_id", 'LEFT')
                    ->join("department ON department.id = tenant_user_department.department_id", 'LEFT')
                    ->field($queryFields)->where(['supplier.id' => ['IN', array_values($supplierIdList)]])->order('supplier.created desc')
                    ->select();
            }

            $tenantAuthenticationModel = model(TenantAuthenticationModel::class);
            $tenantIds = array_column($data, 'from_tenant_id', 'from_tenant_id');

            $userIds = array_column($data, 'user_id', 'user_id');
            $createdByIds = array_column($data, 'created_by', 'created_by');
            $userIds = array_merge($userIds, $createdByIds);
            $users = [];
            if (!empty($userIds)) {
                $users = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIds)]])->select();
                $users = array_column($users, null, 'id');
            }

            if (!empty($tenantIds)) {
                $tenantAuthenticationData = $tenantAuthenticationModel->where(['tenant_id' => ['IN', implode(',', $tenantIds)]])
                    ->field("fdd_auth_status_desc,reasons_for_failure,secrecy_level,company_customer_service,service_category,json,company_business_scope,unified_social_credit_code,company_registered_address,legal_id_period_end,legal_phone,legal_id_number,fdd_auth_url,fdd_transaction_no", true)
                    ->select();
                if (!empty($tenantAuthenticationData)) {
                    //每个供应商 对应不同分类的等级数据
                    foreach ($tenantAuthenticationData as &$authenticationDatum) {
                        CommonService::getFormatAttrData($this->tenantAuthenticationModel, $authenticationDatum);
                    }
                    $tenantAuthenticationDataAssoc = array_column($tenantAuthenticationData, null, 'tenant_id');
                    $tenantStepCategoryLevelModel = model(TenantStepCategoryLevelModel::class);
                    $tenantStepCategoryLevelData = $tenantStepCategoryLevelModel
                        ->where([
                            'tenant_id' => ['IN', implode(',', $tenantIds)]
                        ])
                        ->field("uuid,created,updated,created_by", true)
                        ->select();
                    $tenantStepCategoryLevelData = array_group_by($tenantStepCategoryLevelData, 'tenant_id');
                    $data = array_map(function ($item) use ($tenantAuthenticationDataAssoc, $tenantStepCategoryLevelData, $users) {
                        $item['authentication'] = $tenantAuthenticationDataAssoc[$item['from_tenant_id']] ?? null;
                        $item['level_data'] = $tenantStepCategoryLevelData[$item['from_tenant_id']] ?? null;
                        $item['creator'] = $users[$item['created_by']] ?? null;
                        $item['user'] = $users[$item['user_id']] ?? null;
                        return $item;
                    }, $data);
                }

            }
            // 通过供应商id合并
            $data = array_values(array_column($data, null, 'id'));
        }

        return [
            "total" => $total,
            "rows" => $data
        ];
    }

    /**
     * 获取供应商和客户列表
     * @param $param
     * @param $tenantId
     * @return array
     */
    public function getSupplierCustomerList($param, $tenantId)
    {
        $filter = [
            'supplier.type' => 'outside',
            'bta.status' => 'active',
            'ata.status' => 'active',
            'ata.fdd_cert_status' => '1',
            'ata.fdd_auth_status' => '4',
            'bta.fdd_cert_status' => '1',
            'bta.fdd_auth_status' => '4',
            "_logic" => 'AND'
        ];

        $businessMode = $this->optionService->getBusinessMode();
        if ($businessMode === OptionsService::BUSINESS_MODE_BOTH_SIDES) {
            $filter[] = ["supplier.from_tenant_id" => $tenantId, "supplier.tenant_id" => $tenantId, "_logic" => 'OR'];
            $filter['supplier.framework_agreement_status'] = 'wait_for_sign';
        } elseif ($businessMode === OptionsService::BUSINESS_MODE_TRIPARTITE) {
            $filter[] = [
                ["supplier.from_tenant_id" => $tenantId,
                    "btenant.framework_agreement_status" => 'wait_for_sign'],
                ["supplier.tenant_id" => $tenantId,
                    "atenant.framework_agreement_status" => 'wait_for_sign'
                ],
                "_logic" => 'OR'
            ];
        }

        if (isset($param['filter']['company_name']) && !empty($param['filter']['company_name'])) {
            $companyName = $param['filter']['company_name'];
            $companyNameFilter = [
                ['supplier.tenant_id' => $tenantId, 'bta.company_name' => $companyName],
                ['supplier.from_tenant_id' => $tenantId, 'ata.company_name' => $companyName],
                "_logic" => 'OR'
            ];
            $filter[] = $companyNameFilter;
        }

        $page = $param['page'] ?? [1, C("database.database_max_select_rows")];

        $supplierModel = model(SupplierModel::class);
        // 查询数据
        $queryFields = [
            'supplier.id',
            'supplier.user_id',
            'supplier.type',
            'supplier.tenant_id',
            'supplier.from_tenant_id',
            'supplier.step_category_ids',
            'supplier.created',
            'supplier.updated',
            'supplier.created_by',
            'supplier.framework_agreement_contract_id',
            'supplier.framework_agreement_status',
            'user.name as user_name',
            'user.phone',
        ];

        $supplierQuery = $supplierModel;
        if ($businessMode === OptionsService::BUSINESS_MODE_TRIPARTITE) {
            $supplierQuery = $supplierQuery->join('tenant btenant ON btenant.id=supplier.from_tenant_id')
                ->join('tenant atenant ON atenant.id=supplier.tenant_id');
        }
        $data = $supplierQuery
            ->join("LEFT JOIN tenant_authentication as bta ON bta.tenant_id = supplier.from_tenant_id")
            ->join("LEFT JOIN tenant_authentication as ata ON ata.tenant_id = supplier.tenant_id")
            ->field('supplier.id')
            ->where($filter)
            ->group('supplier.id')
            ->page(...$page)
            ->order('supplier.created desc')
            ->select();

        if (empty($data)) {
            return [];
        }

        $supplierIdList = array_column($data, 'id', 'id');
        $data = $supplierModel
            ->join("LEFT JOIN user ON user.id=supplier.user_id")
            ->field($queryFields)->where(['supplier.id' => ['IN', array_values($supplierIdList)]])->order('supplier.created desc')
            ->select();
        $tenantAuthenticationModel = model(TenantAuthenticationModel::class);
        $userIds = [];
        $outSideTenantIds = [];
        foreach ($data as $dataItem) {
            $outSideTenantIds[$dataItem['from_tenant_id']] = $dataItem['from_tenant_id'];
            $outSideTenantIds[$dataItem['tenant_id']] = $dataItem['tenant_id'];
            $userIds[$dataItem['user_id']] = $dataItem['user_id'];
            $userIds[$dataItem['created_by']] = $dataItem['created_by'];
        }

        unset($outSideTenantIds[$tenantId]);

        $users = [];
        if (!empty($userIds)) {
            $users = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIds)]])->select();
            $users = array_column($users, null, 'id');
        }

        if (!empty($outSideTenantIds)) {
            $tenantAuthenticationData = $tenantAuthenticationModel->where(['tenant_id' => ['IN', implode(',', $outSideTenantIds)]])
                ->field("fdd_cert_status,fdd_auth_status_desc,reasons_for_failure,secrecy_level,company_customer_service,service_category,json,company_business_scope,unified_social_credit_code,company_registered_address,legal_id_period_end,legal_phone,legal_id_number,fdd_auth_status,fdd_auth_url,fdd_transaction_no", true)
                ->select();

            if (!empty($tenantAuthenticationData)) {
                //每个供应商 对应不同分类的等级数据
                foreach ($tenantAuthenticationData as &$authenticationDatum) {
                    CommonService::getFormatAttrData($this->tenantAuthenticationModel, $authenticationDatum);
                }
                $tenantAuthenticationDataAssoc = array_column($tenantAuthenticationData, null, 'tenant_id');
                $tenantStepCategoryLevelData = model(TenantStepCategoryLevelModel::class)
                    ->where(['tenant_id' => ['IN', implode(',', $outSideTenantIds)]])
                    ->field("uuid,created,updated,created_by", true)
                    ->select();
                $tenantStepCategoryLevelData = array_group_by($tenantStepCategoryLevelData, 'tenant_id');
                $data = array_map(function ($item) use ($tenantAuthenticationDataAssoc, $tenantStepCategoryLevelData, $users, $tenantId) {
                    if ($tenantId != $item['from_tenant_id']) {
                        $item['authentication'] = $tenantAuthenticationDataAssoc[$item['from_tenant_id']] ?? null;
                        $item['type'] = 'supplier';
                    }

                    if ($tenantId != $item['tenant_id']) {
                        $item['authentication'] = $tenantAuthenticationDataAssoc[$item['tenant_id']] ?? null;
                        $item['type'] = 'customer';
                    }

                    $item['level_data'] = $tenantStepCategoryLevelData[$item['from_tenant_id']] ?? null;
                    $item['creator'] = $users[$item['created_by']] ?? null;
                    $item['user'] = $users[$item['user_id']] ?? null;
                    return $item;
                }, $data);
            }
        }

        // 通过供应商id合并
        $data = array_values(array_column($data, null, 'id'));

        return $data;
    }


    /**
     * 获取供应商列表 tenant_id 为当前租户
     * @param $currentUserId
     * @param $currentTenantId
     * @param $param
     * @return array
     */
    public function getSupplierList($currentUserId, $currentTenantId, $param)
    {
        $tenantUserModel = model(TenantUserModel::class);
        $tenantUser = $tenantUserModel->where(['user_id' => $currentUserId, 'status' => 'active'])->find();
        if (empty($tenantUser)) {
            throw_strack_exception('Illegal operation', ErrorCode::ILLEGAL_OPERATION);
        }
        $supplierTypeFilter = $param['filter']['type'] ?? "";
        $stepCategoryIdFilter = $param['filter']['supplier.step_category_ids'] ?? null;
        $groupTenantType = $param['filter']['group_tenant_type'] ?? null;
        $personInCharge = $param['filter']['person_in_charge'] ?? null;
        $supplierIdFilter = $param['filter']['supplier.id'] ?? 0;
        $filter = [
            'supplier.tenant_id' => $tenantUser['tenant_id'],
        ];
        if (!empty($supplierIdFilter)) {
            $filter['supplier.id'] = $supplierIdFilter;
        }

        if (!empty($supplierTypeFilter)) {
            $filter['supplier.type'] = $supplierTypeFilter;
//            if ($supplierTypeFilter == "inside") {
//
//            } else
//

            // 2022-12 更新 -> 【可以添加未认证的供应商】
            if ($supplierTypeFilter == "outside") {

                // 认证状态
                // $filter['tenant_authentication.status'] = ['IN', ['active', 'to_be_reviewed']];
                if (!empty($param['filter']['tenant_authentication_status'])) {
                    $filter['tenant_authentication.status'] = [
                        'IN',
                        (array)$param['filter']['tenant_authentication_status']
                    ];
                }
                // FDD证书生成状态
                if (!empty($param['filter']['tenant_authentication_fdd_cert_status'])) {
                    $filter['tenant_authentication.fdd_cert_status'] = $param['filter']['tenant_authentication_fdd_cert_status'];
                }
                // FDD认证状态
                if (!empty($param['filter']['tenant_authentication_fdd_auth_status'])) {
                    $filter['tenant_authentication.fdd_auth_status'] = $param['filter']['tenant_authentication_fdd_auth_status'];
                }
//                $filter['tenant_authentication.status'] = "active";
//                $filter['tenant_authentication.fdd_cert_status'] = "1";
//                $filter['tenant_authentication.fdd_auth_status'] = "4";

            }
            if (isset($param['filter']['company_name']) && !empty($param['filter']['company_name'])) {
                $filter['tenant_authentication.company_name'] = $param['filter']['company_name'];
            }

        }
        // 支持框架合同状态筛选
        if (!empty($param['filter']['framework_agreement_status'])) {
            $businessMode = $this->optionService->getBusinessMode();
            if ($businessMode === OptionsService::BUSINESS_MODE_BOTH_SIDES) {
                $filter[] = [
                    [
                        'supplier.framework_agreement_status' => $param['filter']['framework_agreement_status'],
                        'supplier.type' => 'outside',
                    ],
                    'supplier.type' => 'inside',
                    '_logic' => 'or'
                ];
                $filter['supplier.framework_agreement_status'] = $param['filter']['framework_agreement_status'];
            } else if ($businessMode === OptionsService::BUSINESS_MODE_TRIPARTITE) {
                $filter[] = [
                    [
                        'tenant.framework_agreement_status' => $param['filter']['framework_agreement_status'],
                        'supplier.type' => 'outside',
                    ],
                    'supplier.type' => 'inside',
                    '_logic' => 'or'
                ];
            }
        }

        if (!empty($stepCategoryIdFilter)) {
            $stepCategoryIdFilterValues = '';
            foreach ($stepCategoryIdFilter as $stepCategoryIdFilterValue) {
                $stepCategoryIdFilterValues .= "FIND_IN_SET('{$stepCategoryIdFilterValue}' , supplier.step_category_ids) OR ";
            }
            $stepCategoryIdFilterValues = trim($stepCategoryIdFilterValues, ' OR');
            $filter[] = [
                '_string' => $stepCategoryIdFilterValues
            ];
        }

        // 集团 内部还是外部
        if ($groupTenantType == 'inside') { // 内部
            $tenantGroupData = model(TenantGroupMemberModel::class)->where(['tenant_id' => $currentTenantId])->column('tenant_group_id');
            $tenantGroupInsideIds = model(TenantGroupMemberModel::class)->where(['tenant_group_id' => ['IN', $tenantGroupData]])->column('tenant_id');
            $filter[] = [
                'supplier.from_tenant_id' => [
                    'IN', $tenantGroupInsideIds
                ]
            ];
        }
        if ($groupTenantType == 'outside') { // 外部
            $tenantGroupData = model(TenantGroupMemberModel::class)->where(['tenant_id' => $currentTenantId])->column('tenant_group_id');
            $tenantGroupInsideIds = model(TenantGroupMemberModel::class)->where(['tenant_group_id' => ['IN', $tenantGroupData]])->column('tenant_id');
            $filter[] = [
                'supplier.from_tenant_id' => [
                    'NOT IN', $tenantGroupInsideIds
                ]
            ];
        }
        // 负责人
        if (!empty($personInCharge)) {
            $filter[] = [
                'tenant_authentication.person_in_charge' => ['LIKE', "%$personInCharge%"]
            ];
        }

        // 过滤租户状态
        if (!empty($param['filter']['tenant.status'])) {
            $filter['tenant.status'] =  $param['filter']['tenant.status'];
        }

        return $this->select($param, $filter);
    }


    /**
     * 通过手机号搜索供应商 (已经实名认证通过的) 待添加的
     * 签署过框架协议的
     * @param $currentUserId
     * @param $param
     * @return array|mixed
     * @deprecated 2023年5月19日
     */
    public function getSupplierByPhone($currentUserId, $param)
    {

        $tenantUserModel = model(TenantUserModel::class);
        //查出当前用户租户
        $tenantUser = $tenantUserModel->field('tenant_id')
            ->where([
                'user_id' => $currentUserId,
                'status' => 'active',
            ])
            ->find();

        //查出制片角色的ID
        $optionService = new OptionsService();
        $codeStr = $optionService->getOptionsConfigItemData('supplier_settings', 'role_code');
        $roleData = [];
        if (!empty($codeStr)) {
            $roleFilter = [
                'code' => ['IN', $codeStr],
            ];
            $roleData = model(RoleModel::class)->field('id')->where($roleFilter)->select();
        }

        $resData = [];
        if (!empty($roleData)) {

            $businessMode = $this->optionService->getBusinessMode();

            // 供应商只查询已经实名认证过的 证书状态通过的
            $filter = [
                'user.phone' => $param['filter']['phone'],
                'tenant_user_role.role_id' => ['IN', array_column($roleData, 'id')],
                'tenant_user.tenant_id' => ['NEQ', $tenantUser['tenant_id']],
                'tenant_authentication.status' => 'active',
                'tenant_authentication.fdd_cert_status' => '1',
                'tenant_authentication.fdd_auth_status' => '4',
                '_string' => "supplier.id is null"
            ];

            if ($businessMode === OptionsService::BUSINESS_MODE_TRIPARTITE) {
                // 如果是平台三方模式 那么需要签署框架协议才能查询出来
                $filter['tenant.framework_agreement_status'] = 'signed';
            }


            $maxPageSize = C("database.database_max_select_rows");
            $page = "1, {$maxPageSize}";

            $resData = $tenantUserModel
                ->join("tenant ON tenant.id = tenant_user.tenant_id")
                ->join("user ON user.id = tenant_user.user_id")
                ->join('tenant_user_department on tenant_user.id = tenant_user_department.tenant_user_id', 'LEFT')
                ->join('tenant_user_role on tenant_user.id = tenant_user_role.tenant_user_id', 'LEFT')
                ->join("tenant_authentication ON tenant.id=tenant_authentication.tenant_id", 'LEFT')
                ->join("supplier ON supplier.user_id = tenant_user.user_id AND supplier.from_tenant_id = tenant_user.tenant_id AND supplier.tenant_id = {$tenantUser['tenant_id']}", 'LEFT')
                ->field('CONCAT(tenant_user.tenant_id,\'#\',tenant_user.user_id) as group_str,tenant_user.id,tenant_user.user_id,tenant_user.tenant_id,tenant_user.status,tenant_user.created,tenant_user_department.department_id,tenant_user_role.role_id,user.name as user_name,user.phone,tenant.name as from_tenant_name,tenant_authentication.status as tenant_authentication_status')
                ->where($filter)
                ->page($page)
                ->order('created desc')
                ->select();

            if (!empty($resData)) {
                $resData = array_column($resData, null, 'group_str');
                $resData = array_values($resData);
                $tenantIds = array_column($resData, 'tenant_id', 'tenant_id');
                if (!empty($tenantIds)) {

                    $tenantAuthenticationModel = model(TenantAuthenticationModel::class);
                    $tenantAuthenticationData = $tenantAuthenticationModel->where(['tenant_id' => ['IN', implode(',', $tenantIds)]])
                        ->field("fdd_cert_status,fdd_auth_status_desc,reasons_for_failure,secrecy_level,company_customer_service,service_category,json,company_business_scope,unified_social_credit_code,company_registered_address,legal_id_period_end,legal_phone,legal_id_number,fdd_auth_status,fdd_auth_url,fdd_transaction_no", true)
                        ->select();
                    $tenantAuthenticationDataAssoc = array_column($tenantAuthenticationData, null, 'tenant_id');

                    //每个供应商 对应不同分类的等级数据
                    $tenantStepCategoryLevelModel = model(TenantStepCategoryLevelModel::class);
                    $tenantStepCategoryLevelData = $tenantStepCategoryLevelModel
                        ->where([
                            'tenant_id' => ['IN', implode(',', $tenantIds)]
                        ])
                        ->field("tenant_id,step_category_id,step_category_name,step_category_code,level")
                        ->select();

                    if (!empty($tenantStepCategoryLevelData)) {
                        $tenantStepCategoryLevelData = array_group_by($tenantStepCategoryLevelData, 'tenant_id');
                        $tenantStepCategoryData = array_map(function ($item) {
                            $item = array_column($item, 'step_category_id');
                            return $item;
                        }, $tenantStepCategoryLevelData);

                        //填充租户认证的工序分类数据
                        $resData = array_map(function ($item) use ($tenantStepCategoryData, $tenantStepCategoryLevelData, $tenantAuthenticationDataAssoc) {
                            $item['step_category_ids'] = $tenantStepCategoryData[$item['tenant_id']] ?? [];
                            $item['step_category_ids'] = implode(',', $item['step_category_ids']);
                            $item['level_data'] = $tenantStepCategoryLevelData[$item['tenant_id']] ?? [];
                            $item['authentication'] = $tenantAuthenticationDataAssoc[$item['tenant_id']] ?? [];
                            return $item;
                        }, $resData);
                    }
                }
            }
        }


        return $resData;
    }

    /**
     * 查询供应商
     * @param array $param
     * @param $tenantId
     * @return mixed|null
     */
    public function getSupplier(array $param, $tenantId)
    {
        if (empty($param['filter'])) {
            $param['filter'] = [
                'supplier.tenant_id' => $tenantId
            ];
        } else {
            $param['filter'] = append_filter_param($param, 'supplier', 'tenant_id', $tenantId);
        }
        $supplierTypeFilter = $param['filter']['type'] ?? "";
        if (!empty($supplierTypeFilter)) {
            $param['filter'] = append_filter_param($param, 'supplier', 'type', $supplierTypeFilter);
//            if ($supplierTypeFilter == "inside") {
//                // 内部供应商
//            } else

            if ($supplierTypeFilter == "outside") {
                //外部供应商
                $param['filter'] = append_filter_param($param, 'tenant_authentication', 'status', "active");
                $param['filter'] = append_filter_param($param, 'tenant_authentication', 'fdd_cert_status', 1);
                $param['filter'] = append_filter_param($param, 'tenant_authentication', 'fdd_auth_status', 4);
            }
        }


        return $this->find($param['filter']);
    }

    /**
     * 供应商查询
     * @param array $filter
     * @return mixed|null
     * @throws \Exception
     */
    public function find(array $filter)
    {
        $supplierModel = model(SupplierModel::class);
        $queryFields = [
            'supplier.id',
            'supplier.user_id',
            'supplier.type',
            'supplier.tenant_id',
            'supplier.from_tenant_id',
            'supplier.step_category_ids',
            'supplier.created',
            'supplier.updated',
            'supplier.created_by',
            'supplier.framework_agreement_contract_id',
            'supplier.framework_agreement_status',
            'user.name as user_name',
            'user.phone',
            'tenant.name as from_tenant_name',
            'tenant_user.id as tenant_user_id',
        ];
        $data = $supplierModel
            ->join("user ON user.id=supplier.user_id")
            ->join("tenant ON tenant.id=supplier.from_tenant_id")
            ->join("LEFT JOIN tenant_authentication ON tenant_authentication.tenant_id = supplier.from_tenant_id")
            ->join("LEFT JOIN tenant_user ON supplier.user_id = tenant_user.user_id AND supplier.from_tenant_id = tenant_user.tenant_id")
            ->field(implode(',', $queryFields))
            ->where($filter)
            ->find();

        if (empty($data)) {
            return null;
        }
        $tenantUserIdList = [$data['tenant_user_id']];
        $tenantUserDepartmentRoleInfoList = TenantUserService::getInstance()->getTenantUserListDepartmentRole($tenantUserIdList);
        $data['department_info'] = $data['role_info'] = [];
        if (isset($tenantUserDepartmentRoleInfoList[$data['tenant_user_id']])) {
            $data = array_merge($data, $tenantUserDepartmentRoleInfoList[$data['tenant_user_id']]);
        }
        $userIds = [$data['created_by'], $data['user_id']];
        $users = [];
        if (!empty($userIds)) {
            $users = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIds)]])->select();
            $users = array_column($users, null, 'id');
        }
        $tenantAuthenticationData = $this->tenantAuthenticationModel
            ->where(['tenant_id' => $data['from_tenant_id']])
            ->field("fdd_cert_status,fdd_auth_status_desc,reasons_for_failure,fdd_auth_url,fdd_transaction_no", true)
            ->find();
        if (!empty($tenantAuthenticationData)) {
            CommonService::getFormatAttrData($this->tenantAuthenticationModel, $tenantAuthenticationData);
        }
        //每个供应商 对应不同分类的等级数据
        $data['authentication'] = $tenantAuthenticationData;
        $data['level_data'] = model(TenantStepCategoryLevelModel::class)
            ->where([
                'tenant_id' => $data['from_tenant_id']
            ])
            ->field("uuid,created,updated,created_by", true)
            ->select();
        $data['creator'] = $users[$data['created_by']] ?? null;
        $data['user'] = $users[$data['user_id']] ?? null;

        return $data;
    }

    /**
     * 基本查询
     * @param $filter
     * @return array|false|mixed|string|null
     */
    public function baseFind($filter)
    {
        $row = $this->supplierModel->where($filter)->find();
        if (!empty($row)) {
            CommonService::getFormatAttrData($this->supplierModel, $row);
        }
        return $row;
    }

    /**
     * 创建
     * @param array $param
     * @param int $tenantId
     * @return array|bool
     * @throws Exception
     */
    public function create($param, $tenantId)
    {
        $data = $param['data'];
        if ($data['type'] === 'outside') {
            // 检查当前租户是否添加过该供应商
            $uniqueCheck = $this->supplierModel->where(['tenant_id' => $tenantId, 'type' => 'outside', 'from_tenant_id' => $data['from_tenant_id']])->count();
            if ($uniqueCheck) {
                throw_strack_exception('tenant already add to your supplier list', ErrorCode::SUPPLIER_ALREADY_ADDED);
            }
        }
        $data['create_tenant_id'] = $tenantId; // 创建者租户id
        $commonService = CommonService::instance('supplier');
        $commonService->setCurrentModuleCode('supplier');
        return $commonService->create($data);
    }

    /**
     * 生成供应商负责人
     * @param $tenantIds
     * @return array
     * @throws \Exception
     */
    public function generateSupplierChargePerson($tenantIds)
    {
        if (empty($tenantIds)) {
            return [];
        }

        //查出制片角色的ID

        $codeStr = OptionsService::getInstance()->getOptionsConfigItemData('supplier_settings', 'role_code');
        $roleData = [];
        if (!empty($codeStr)) {
            $roleFilter = [
                'code' => ['IN', $codeStr],
            ];
            $roleData = model(RoleModel::class)->field('id')->where($roleFilter)->select();
        }

        if (empty($roleData)) {
            throw new LogicException('role code not exist', ErrorCode::CONFIG_NOT_EXIST);
        }

        $roleData = array_column($roleData, 'id');

        $tenantUser = model(TenantUserModel::class)
            ->join('tenant_user_role on tenant_user_role.tenant_user_id = tenant_user.id')
            ->join("user on tenant_user.user_id = user.id")
            ->field('tenant_id')
            ->where([
                'tenant_user.tenant_id' => ["IN", $tenantIds],
                'tenant_user_role.role_id' => ["IN", $roleData],
                'user.active' => 1,
            ])
            ->field("tenant_id,user_id")
            ->group("tenant_id")
            ->select();

        //如果有公司没有,则需要中断
        if (count($tenantIds) != count($tenantUser)) {
            throw new LogicException('role code not exist', ErrorCode::TENANT_SPECIFY_ROLE_USER_NOT_EXIST);
        }

        return array_column($tenantUser, 'user_id', 'tenant_id');
    }

    /**
     * 添加集团供应商
     * @param $params
     * @throws \Exception
     */
    public function addTenantGroupSupplier($params)
    {
        //排除掉自己
        $currentTenantId = $params['tenant_id'];
        $tenantGroupMemberList = model(TenantGroupMemberModel::class)
            ->where(['tenant_group_id' => $params['tenant_group_id'], 'tenant_id' => ['NEQ', $currentTenantId]])->field("tenant_id")->select();

        //需要为每个公司添加供应商 , 以及需要为自家公司添加添加其他成员供应商

        if (!empty($tenantGroupMemberList)) {
            $tenantIds = array_column($tenantGroupMemberList, 'tenant_id');

            //查询是否存在供应商
            $supplierData = [];
            foreach ($tenantIds as $tenantId) {
                $supplierData["{$currentTenantId}_{$tenantId}"] = [
                    'tenant_id' => $currentTenantId,
                    'from_tenant_id' => $tenantId
                ];
                $supplierData["{$tenantId}_{$currentTenantId}"] = [
                    'tenant_id' => $tenantId,
                    'from_tenant_id' => $currentTenantId
                ];
            }

            $supplierFilter = array_values($supplierData);
            $supplierFilter["_logic"] = "OR";
            $supplierFilter = [
                $supplierFilter,
                "type" => "outside",
            ];

            //找出没有的添加
            $supplierList = model(SupplierModel::class)->where($supplierFilter)->select();
            foreach ($supplierList as $supplierItem) {
                $supplierTenantId = $supplierItem["tenant_id"];
                $supplierFromTenantId = $supplierItem["from_tenant_id"];
                if (isset($supplierData["{$supplierTenantId}_{$supplierFromTenantId}"])) {
                    unset($supplierData["{$supplierTenantId}_{$supplierFromTenantId}"]);
                }
            }

            //如果存在新的供应商
            if (!empty($supplierData)) {
                $supplierData = array_values($supplierData);
                $supplierFromTenantIds = array_unique(array_column($supplierData, 'from_tenant_id'));
                //获取供应商负责人 以及 租户的对应的工序分类
                $supplierChargePerson = SupplierService::getInstance()->generateSupplierChargePerson($supplierFromTenantIds);
                $tenantStepCategoryList = model(TenantStepCategoryLevelModel::class)->where(['tenant_id' => ["IN", $supplierFromTenantIds]])->field("tenant_id,step_category_id")->select();

                // 建立 映射 ["tenant_id"=>["step_category_id"]]
                $tenantStepCategoryMap = [];
                foreach ($tenantStepCategoryList as $tenantStepCategoryItem) {
                    $tenantStepCategoryMap[$tenantStepCategoryItem["tenant_id"]][$tenantStepCategoryItem["step_category_id"]] = $tenantStepCategoryItem["step_category_id"];
                }

                //组装数据 user_id,step_category_ids
                $userId = $params['user_id'];
                $supplierData = array_map(function ($supplierDataItem) use ($userId, $supplierChargePerson, $tenantStepCategoryMap) {
                    if (isset($supplierChargePerson[$supplierDataItem["from_tenant_id"]])) {
                        $supplierDataItem["user_id"] = $supplierChargePerson[$supplierDataItem["from_tenant_id"]];
                    }

                    if (isset($tenantStepCategoryMap[$supplierDataItem["from_tenant_id"]])) {
                        $supplierDataItem["step_category_ids"] = join(",", $tenantStepCategoryMap[$supplierDataItem["from_tenant_id"]]);
                    }
                    $supplierDataItem["type"] = "outside";
                    $supplierDataItem["created"] = time();
                    $supplierDataItem["updated"] = time();
                    $supplierDataItem["created_by"] = $userId;
                    return $supplierDataItem;
                }, $supplierData);

                //添加供应商
                model(SupplierModel::class)->addAll($supplierData);
            }
        }
    }

    /**
     * 根据名称搜索供应商
     * @param $currentTenantId
     * @param $param
     * @return array|false|mixed|string
     */
    public function getSupplierByName($currentTenantId, $param)
    {
        $tenantModel = model(TenantModel::class);
        $businessMode = $this->optionService->getBusinessMode();

        // 供应商只查询已经实名认证过的 证书状态通过的
        $filter = [
            'tenant.name' => ['LIKE', "%" . $param['filter']['name'] . "%"],
            'tenant.id' => ['NEQ', $currentTenantId]
        ];

        if ($businessMode === OptionsService::BUSINESS_MODE_TRIPARTITE) {
            // 如果是平台三方模式 那么需要签署框架协议才能查询出来
            $filter['tenant.framework_agreement_status'] = 'signed';
        }

        // 供应商服务环节筛选
        $supplierStepCategoryIds = $param['filter']['supplier.step_category_ids'] ?? [];
        if (!empty($supplierStepCategoryIds) && is_array($supplierStepCategoryIds)) {
            $tenantIds = model(TenantStepCategoryLevelModel::class)->where(['step_category_id' => ['IN', $supplierStepCategoryIds]])->column('tenant_id');
            if (!empty($tenantIds)) {
                $filter['tenant.id'] = [
                    'IN', $tenantIds
                ];
            }
        }

        $maxPageSize = C("database.database_max_select_rows");
        $page = "1, {$maxPageSize}";

        // 根据租户状态搜索
        if (!empty($param['filter']['tenant.status'])) {
            $filter['tenant.status'] = $param['filter']['tenant.status'];
        }

        $resData = $tenantModel->alias('tenant')
            ->join("LEFT JOIN tenant_authentication ON tenant.id=tenant_authentication.tenant_id")
            ->field('tenant.id as tenant_id,tenant.name as from_tenant_name,tenant_authentication.status as tenant_authentication_status')
            ->where($filter)
            ->page($page)
            ->order('tenant.created desc')
            ->select();

        if (!empty($resData)) {
            $resData = array_column($resData, null, 'group_str');
            $resData = array_values($resData);
            $tenantIds = array_column($resData, 'tenant_id', 'tenant_id');
            if (!empty($tenantIds)) {
                $tenantAuthenticationModel = model(TenantAuthenticationModel::class);
                $tenantAuthenticationData = $tenantAuthenticationModel->where(['tenant_id' => ['IN', implode(',', $tenantIds)]])
                    ->field("fdd_cert_status,fdd_auth_status_desc,reasons_for_failure,secrecy_level,company_customer_service,service_category,json,company_business_scope,unified_social_credit_code,company_registered_address,legal_id_period_end,legal_phone,legal_id_number,fdd_auth_url,fdd_transaction_no", true)
                    ->select();
                $tenantAuthenticationDataAssoc = array_column($tenantAuthenticationData, null, 'tenant_id');
                // 查询出【供应商】是否添加过
                $supplierData = model(SupplierModel::class)->where(['tenant_id' => $currentTenantId, 'from_tenant_id' => ['IN', implode(',', $tenantIds)]])->column("from_tenant_id");
                // 查询出【客户】是否添加过
                $customerData = model(SupplierModel::class)->where(['from_tenant_id' => $currentTenantId, 'tenant_id' => ['IN', implode(',', $tenantIds)]])->column("tenant_id");
                //每个供应商 对应不同分类的等级数据
                $tenantStepCategoryLevelModel = model(TenantStepCategoryLevelModel::class);
                $tenantStepCategoryLevelData = $tenantStepCategoryLevelModel
                    ->where([
                        'tenant_id' => ['IN', implode(',', $tenantIds)]
                    ])
                    ->field("tenant_id,step_category_id,step_category_name,step_category_code,level")
                    ->select();

                if (!empty($tenantStepCategoryLevelData)) {
                    $tenantStepCategoryLevelData = array_group_by($tenantStepCategoryLevelData, 'tenant_id');
                    $tenantStepCategoryData = array_map(function ($item) {
                        $item = array_column($item, 'step_category_id');
                        return $item;
                    }, $tenantStepCategoryLevelData);

                    //填充租户认证的工序分类数据
                    $resData = array_map(function ($item) use ($tenantStepCategoryData, $tenantStepCategoryLevelData, $tenantAuthenticationDataAssoc, $supplierData, $currentTenantId, $customerData) {
                        $item['step_category_ids'] = $tenantStepCategoryData[$item['tenant_id']] ?? [];
                        $item['step_category_ids'] = implode(',', $item['step_category_ids']);
                        $item['level_data'] = $tenantStepCategoryLevelData[$item['tenant_id']] ?? [];
                        $item['authentication'] = $tenantAuthenticationDataAssoc[$item['tenant_id']] ?? [];
                        $item['add'] = in_array($item['tenant_id'], $supplierData);
                        $item['customer_add'] = in_array($item['tenant_id'], $customerData);
                        return $item;
                    }, $resData);
                }
            }
        }

        return $resData;
    }
}
